<template>
  <view class="container">
    <!-- Tab Bar -->
    <view class="tab-bar-container">
      <view class="tab-bar">
        <view
            v-for="(tab, index) in ['设备列表', '设备配网']"
            :key="index"
            class="tab-item"
            :class="{ active: currentTab === index, disabled: index === 1 && isConfigTabDisabled }"
            @click="onClickTab({ currentIndex: index })"
        >
          <text>{{ tab }}</text>
        </view>
      </view>
      <view class="tab-bar-spacer"></view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 蓝牙设备列表 Tab -->
      <view v-if="currentTab === 0" class="device-list-content">
        <scroll-view scroll-y class="device-scroll-view">
          <view
              v-for="device in deviceList"
              :key="device.id"
              class="device-item"
              @click="bindViewConnect(device.deviceId)"
          >
            <view class="device-icon-wrapper">
              <image :src="device.image || '/static/default-device-icon.png'" class="device-actual-image"></image>
            </view>
            <view class="device-info">
              <text class="device-name">{{ device.name || '未知设备' }}</text>
            </view>
          </view>
          <view v-if="deviceList.length === 0 && isDiscovering" class="empty-list">
            <text>扫描中...</text>
          </view>
          <view v-if="deviceList.length === 0 && !isDiscovering && isEmptyListDisplayed" class="empty-list">
            <text>暂未扫描到设备</text>
          </view>
        </scroll-view>
      </view>

      <!-- 设备配网 Tab -->
      <view v-if="currentTab === 1" class="network-config-content">
        <view v-if="selectedDevice" class="selected-device-display">
          <view class="device-icon-wrapper">
            <image :src="selectedDevice.image || '/static/default-device-icon.png'" class="device-actual-image"></image>
          </view>
          <view class="device-info">
            <text class="device-name">{{ selectedDevice.name || '未知设备' }}</text>
          </view>
        </view>
        <view class="form">
          <text>Wi-Fi名称</text>
          <view class="form-item">
            <input v-model="ssid" placeholder="请输入WiFi名称" maxlength="32" />
          </view>
		  
          <text>Wi-Fi密码</text>
			<view class="form-item password-input-wrapper">
			  <input
				v-model="password"
				type="text"
				:password="!showPassword"
				placeholder="请输入WiFi密码"
				maxlength="64"
			  />
			  <image
				:src="showPassword ? '/static/icons/eye-open.png' : '/static/icons/eye-close.png'"
				class="eye-icon"
				@click="showPassword = !showPassword"
			  />
			</view>
          <button class="submit-btn" @click="startConfig">发送配网</button>
        </view>
      </view>
    </view>

    <!-- Loading 弹窗 -->
    <uni-popup
        ref="loadingPopup"
        type="center"
        mask="true"
        mask-background-color="rgba(0,0,0,0.0)"
    >
      <view class="custom-fullscreen">
        <view class="loading-box">
          <image class="loading-icon" src="/static/icons/loading.png" mode="widthFix"></image>
          <text class="text-overlay">{{ loadingMessage }}</text>
        </view>
      </view>
    </uni-popup>

    <!-- 配网成功弹窗 -->
    <uni-popup ref="connectSuccessPopup" type="center" :mask-click="false" mask-background-color="rgba(0,0,0,0)">
      <view class="custom-fullscreen">
        <view class="loading-box">
          <image class="success" src="/static/icons/success.png"></image>
          <text class="text-overlay">配网成功</text>
        </view>
      </view>
    </uni-popup>

    <!-- 绑定成功弹窗 -->
    <uni-popup ref="bindSuccessPopup" type="center" :mask-click="false" mask-background-color="rgba(0,0,0,0)">
      <view class="custom-fullscreen">
        <view class="loading-box">
          <image class="success" src="/static/icons/bindSuccess.png"></image>
          <text class="text-overlay">设备绑定成功</text>
        </view>
      </view>
    </uni-popup>

    <!-- 请输入WIFI名称弹窗 -->
    <uni-popup ref="wifiWarnPopup" type="center" :mask-click="false" mask-background-color="rgba(0,0,0,0)">
      <view class="custom-fullscreen">
        <view class="wifi-input-box">
          <text class="wifi-text-overlay">{{ wifiWarnMsg }}</text>
        </view>
      </view>
    </uni-popup>

    <custom-popup
        ref="popupRef"
        type="center"
        :show-footer="false"
        title="提示"
        :mask-click="true"
    >
      <text>{{ popupMessage }}</text>
    </custom-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import md5 from 'md5';
import { filterDevice, writeData, getFrameCTRLValue, isSubcontractor, fetchBLEMTU, actualMtu, SUBTYPE_CUSTOM_DATA } from '@/utils/blufi';
import { bindByDeviceId, getDeviceDetail ,saveBaseInfo} from '../../app/device';
import CustomPopup from '@/components/custom-popup.vue';

const popupRef = ref<InstanceType<typeof CustomPopup> | null>(null);

// 定义蓝牙设备类型
interface BluetoothDevice {
  id: string;
  deviceId: string;
  name: string;
  RSSI: number;
  image?: string;
  [key: string]: any;
}

// 页面状态
const currentTab = ref<number>(0);
const deviceList = reactive<BluetoothDevice[]>([]);
const isDiscovering = ref<boolean>(false);
const showPassword = ref<boolean>(false);
const isEmptyListDisplayed = ref<boolean>(false); // 新增状态缓冲
const loadingPopup = ref<any>(null);
const connectSuccessPopup = ref<any>(null);
const bindSuccessPopup = ref<any>(null);
const wifiWarnPopup = ref<any>(null);
const loadingMessage = ref('');
const bindStatus = ref<number>(null);
const popupMessage = ref('');
const wifiWarnMsg = ref('');
const ssid = ref<string>('');
const password = ref<string>('');
const sequence = ref<number>(0);
const md5Key = ref<number[]>([]);

// 连接状态
const deviceId = ref<string>('');
const serviceId = ref<string>('');
const writeCharId = ref<string>('');
const readCharId = ref<string>('');
const customId = ref('');
const selectedDevice = ref<BluetoothDevice | null>(null);

// 全局配置
const SERVICE_UUID = '0000FFFF-0000-1000-8000-00805F9B34FB';
const CHARACTERISTIC_WRITE_UUID = '0000FF01-0000-1000-8000-00805F9B34FB';
const CHARACTERISTIC_READ_UUID = '0000FF02-0000-1000-8000-00805F9B34FB';
const PACKAGE_VALUE = 0x01;
const PACKAGE_CONTROL_VALUE = 0x00;
const SUBTYPE_NEG = 0x00;
const SUBTYPE_WIFI_MODEl = 0x02;
const SUBTYPE_SET_SSID = 0x02;
const SUBTYPE_SET_PWD = 0x03;
const SUBTYPE_END = 0x03;
const SUBTYPE_SET_SEC_MODE = 0x01;
const DIRECTION_OUTPUT = 0;
const isConfigTabDisabled = ref<boolean>(true);

// 手动 UTF-8 编码函数
const encodeUTF8 = (str: string): number[] => {
  const bytes: number[] = [];
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    if (charCode < 0x80) {
      bytes.push(charCode);
    } else if (charCode < 0x800) {
      bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
    } else if (charCode < 0x10000) {
      bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    } else {
      bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    }
  }
  return bytes;
};

const onClickTab = (e: { currentIndex: number }) => {
  console.log('[onClickTab] Start. Index:', e.currentIndex, 'Current deviceId:', deviceId.value, 'selectedDevice:', selectedDevice.value);

  if (e.currentIndex === 1 && !deviceId.value) {
    currentTab.value = 0;
    return;
  }

  if (e.currentIndex === 0) {
    if (deviceId.value) {
      uni.closeBLEConnection({
        deviceId: deviceId.value,
        success: () => {
          console.log('断开设备:', deviceId.value);
        },
        fail: (err) => {
          console.error('断开连接失败:', JSON.stringify(err, null, 2));
        },
      });
    }

    deviceId.value = '';
    serviceId.value = '';
    writeCharId.value = '';
    readCharId.value = '';
    selectedDevice.value = null;
    getBluDevice();
    isConfigTabDisabled.value = true;
  }

  currentTab.value = e.currentIndex;
};

const getBluDevice = async () => {
  try {
    loadingMessage.value = '设备扫描中...';
    loadingPopup.value?.open();
    isDiscovering.value = true;
    closeBleConnect();
    deviceList.length = 0;
    isEmptyListDisplayed.value = false;
    await clearBluetoothCache();
    await initializeBluetooth();
    const state = await checkBluetoothState();
    if (!state.available) {
      showBluetoothPrompt();
      loadingPopup.value?.close();
      return;
    }

    if (state.discovering) {
      await stopDeviceDiscovery();
    }

    await startDeviceDiscovery();
    fetchBluetoothDevices();
  } catch (err) {
    console.error('初始化蓝牙失败:', JSON.stringify(err, null, 2));
    showBluetoothPrompt();
    loadingPopup.value?.close();
    isEmptyListDisplayed.value = true;
  }
  await delay(1000);
  isDiscovering.value = false;
  if(deviceList.length === 0){
    console.log("设备列表为空------")
    isEmptyListDisplayed.value = true;
  }
  loadingPopup.value?.close();
};

const initializeBluetooth = () => {
  return new Promise<void>((resolve, reject) => {
    uni.openBluetoothAdapter({
      success: () => {
        console.log('蓝牙适配器初始化成功');
        resolve();
      },
      fail: (err) => {
        console.error('蓝牙初始化失败:', JSON.stringify(err, null, 2));
        reject(err);
      },
    });
  });
};

const checkBluetoothState = () => {
  return new Promise<{ available: boolean; discovering: boolean }>((resolve, reject) => {
    uni.getBluetoothAdapterState({
      success: (res) => {
        console.log('蓝牙适配器状态:', res);
        resolve(res);
      },
      fail: (err) => {
        console.error('获取蓝牙状态失败:', JSON.stringify(err, null, 2));
        reject(err);
      },
    });
  });
};

const startDeviceDiscovery = () => {
  return new Promise<void>((resolve, reject) => {
    uni.startBluetoothDevicesDiscovery({
      success: () => {
        console.log('开始扫描蓝牙设备');
        isDiscovering.value = true;
        resolve();
      },
      fail: (err) => {
        console.error('启动扫描失败:', JSON.stringify(err, null, 2));
        if (err.errMsg.includes('already discovering')) {
          console.log('已在扫描中，忽略错误');
          isDiscovering.value = true;
          resolve();
        } else {
          isDiscovering.value = false;
          reject(err);
        }
      },
    });
  });
};

const stopDeviceDiscovery = () => {
  return new Promise<void>((resolve) => {
    if (isDiscovering.value) {
      uni.stopBluetoothDevicesDiscovery({
        success: () => {
          console.log('停止设备扫描');
          isDiscovering.value = false;
          resolve();
        },
        fail: (err) => {
          console.error('停止扫描失败:', err);
          isDiscovering.value = false;
          resolve();
        },
      });
    } else {
      resolve();
    }
  });
};

const fetchBluetoothDevices = () => {
  const knownDeviceIds = new Set<string>();
  uni.getBluetoothDevices({
    success: (res) => {
      console.log('获取设备成功:', res.devices);
      const filteredDevices = filterDevice(res.devices, 'name').map((device) => ({
        ...device,
        id: device.deviceId,
      }));
      console.log('过滤后设备:', filteredDevices);
      const uniqueDevices = filteredDevices.filter((device) => {
        if (knownDeviceIds.has(device.deviceId)) return false;
        knownDeviceIds.add(device.deviceId);
        return true;
      });

      if (uniqueDevices.length > 0) {
        console.log('更新设备列表:', uniqueDevices);
        deviceList.splice(0, deviceList.length, ...uniqueDevices);
        isEmptyListDisplayed.value = false;
      }
    },
    fail: (err) => {
      console.error('获取设备失败:', JSON.stringify(err, null, 2));
      uni.showToast({ title: '获取设备失败', icon: 'none' });
      loadingPopup.value?.close();
      isEmptyListDisplayed.value = true;
    },
  });

  uni.onBluetoothDeviceFound((res) => {
    console.log('发现新设备:', res.devices);
    const filteredDevices = filterDevice(res.devices, 'name').map((device) => ({
      ...device,
      id: device.deviceId,
    }));
    console.log('过滤后设备:', filteredDevices);
    const uniqueDevices = filteredDevices.filter((device) => {
      if (knownDeviceIds.has(device.deviceId)) return false;
      knownDeviceIds.add(device.deviceId);
      return true;
    });

    if (uniqueDevices.length > 0) {
      console.log('追加新设备:', uniqueDevices);
      deviceList.push(...uniqueDevices);
      isEmptyListDisplayed.value = false;
    }
    console.log("已扫描到的设备数量", deviceList.length);
  });

  const checkDiscoveryTimeout = () => {
    setTimeout(() => {
      uni.getBluetoothAdapterState({
        success: (res) => {
          if (!res.discovering && deviceList.length === 0) {
            console.log('扫描结束，未发现设备');
            isEmptyListDisplayed.value = true;
            loadingPopup.value?.close();
            isDiscovering.value = false;
          } else if (deviceList.length > 0) {
            console.log('已发现设备，关闭弹窗');
            loadingPopup.value?.close();
          } else {
            checkDiscoveryTimeout();
          }
        },
        fail: (err) => {
          console.error('检查蓝牙状态失败:', err);
          isEmptyListDisplayed.value = true;
          loadingPopup.value?.close();
          isDiscovering.value = false;
        },
      });
    }, 1000);
  };

  checkDiscoveryTimeout();
};

const clearBluetoothCache = () => {
  return new Promise<void>((resolve, reject) => {
    uni.closeBluetoothAdapter({
      success: () => {
        console.log('蓝牙适配器关闭成功');
        setTimeout(() => {
          uni.openBluetoothAdapter({
            success: () => {
              console.log('蓝牙适配器重新打开成功');
              resolve();
            },
            fail: (err) => {
              console.error('重新打开蓝牙适配器失败:', JSON.stringify(err));
              reject(err);
            },
          });
        }, 1500);
      },
      fail: (err) => {
        console.error('关闭蓝牙适配器失败:', JSON.stringify(err));
        reject(err);
      },
    });
  });
};

const showBluetoothPrompt = () => {
  uni.showModal({
    title: '蓝牙未开启',
    content: '请在手机设置中开启蓝牙并授权小程序使用蓝牙功能',
    confirmText: '重试',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        getBluDevice();
      }
    },
  });
};

const bindViewConnect = async (id: string) => {
  uni.closeBLEConnection({
    deviceId: deviceId.value,
    success: () => {
      console.log('断开设备:', deviceId.value);
    },
    fail: (err) => {
      console.error('断开连接失败:', JSON.stringify(err, null, 2));
    },
  });

  deviceId.value = id;
  loadingMessage.value = '正在连接蓝豆包AI玩具';
  loadingPopup.value?.open();
  try {
    await uni.createBLEConnection({ deviceId: id, timeout: 10000 });
    console.log('蓝牙连接成功:', id);
    const services = await uni.getBLEDeviceServices({ deviceId: id });
    const service = services.services.find((s) => s.uuid.toUpperCase() === SERVICE_UUID);
    if (!service) throw new Error('未找到指定服务');
    serviceId.value = service.uuid;

    const characteristics = await uni.getBLEDeviceCharacteristics({
      deviceId: id,
      serviceId: service.uuid,
    });
    console.log('所有特征值:', characteristics.characteristics);
    const writeChar = characteristics.characteristics.find(
        (c) => c.uuid.toUpperCase() === CHARACTERISTIC_WRITE_UUID
    );
    const readChar = characteristics.characteristics.find(
        (c) => c.uuid.toUpperCase() === CHARACTERISTIC_READ_UUID
    );
    console.log('特征值属性:', readChar?.properties);
    if (!writeChar || !readChar) throw new Error('未找到指定特征值');
    writeCharId.value = writeChar.uuid;
    readCharId.value = readChar.uuid;

    selectedDevice.value = deviceList.find((device) => device.deviceId === id) || null;

    uni.offBLECharacteristicValueChange();

    sequence.value = 0;

    await fetchBLEMTU(deviceId.value);
    console.log(`将使用MTU: ${actualMtu.value} 字节`);

    await new Promise<void>((resolve, reject) => {
      uni.notifyBLECharacteristicValueChange({
        deviceId: id,
        serviceId: service.uuid,
        characteristicId: readCharId.value,
        state: true,
        success: async () => {
          console.log('启用通知成功');
          let packetBuffer = [];
          let expectedSequence = 0;
          uni.onBLECharacteristicValueChange(async (res) => {
            const value = new Uint8Array(res.value);
            const type = value[0] & 0x03;
            const subType = (value[0] >> 2) & 0x3F;
            const sequenceNum = value[2];

            console.log('收到分包:', {
              sequenceNum,
              currentLength: packetBuffer.length,
              data: Array.from(value.slice(6)).map(b => b.toString(16).padStart(2, '0')),
              buffer: packetBuffer.map(b => b.toString(16).padStart(2, '0')),
            });
            console.log('收到蓝牙通知:', JSON.stringify({
              type,
              subType,
              sequenceNum,
              value: Array.from(value),
              rawValue: Array.from(value).map(b => b.toString(16).padStart(2, '0'))
            }, null, 2));

            if (type === PACKAGE_VALUE && subType === SUBTYPE_CUSTOM_DATA) {
              if (sequenceNum === expectedSequence) {
                let dataStartIndex = 6;
                if (sequenceNum === 0 && value[4] === 0xFF && value[5] === 0xA1) {
                  dataStartIndex = 6;
                } else if (sequenceNum > 0) {
                  dataStartIndex = 4;
                }

                const data = Array.from(value.slice(dataStartIndex));
                packetBuffer.push(...data);

                console.log('当前分包数据:', data, '累积buffer:', packetBuffer);

                if (packetBuffer.length >= 36) {
                  const idData = packetBuffer.slice(0, 36);
                  console.log('原始ID数据:', idData, '十六进制:', idData.map(b => b.toString(16).padStart(2, '0')));
                  customId.value = String.fromCharCode(...idData);
                  console.log(`收到设备自定义ID: ${customId.value}`);
                  const userInfo = uni.getStorageSync("userInfo");
                  console.log(userInfo);
				  // 保存设备id
				  await saveBaseInfo(customId.value);
				  await delay(50);
                  const res = await getDeviceDetail(customId.value);
                  console.log('设备详情res:', res);
                  console.log('设备详情res.data:', res.data);
                  if (res.code === '200' && res.data.bindStatus === 1 && res.data.userId !== userInfo.id) {
                    loadingPopup.value?.close();
                    await showPopup("当前设备已被绑定，请解绑后重试");
                    customId.value = '';
                    isConfigTabDisabled.value = true;
                    closeConnectAndSearchBlue();
                    return;
                  } else {
                    currentTab.value = 1;
                    isConfigTabDisabled.value = false;
                  }
                  packetBuffer = [];
                  expectedSequence = sequenceNum + 1;
                  loadingPopup.value?.close();
                }
                expectedSequence++;
              } else {
                console.warn(`序列号不匹配: 期望 ${expectedSequence}, 收到 ${sequenceNum}`);
                packetBuffer = [];
                expectedSequence = sequenceNum;
              }
            } else {
              await showPopup("蓝牙连接失败，请稍后重试");
              closeConnectAndSearchBlue();
              return;
            }
          });

          sendCustomData();
          console.log('已发送自定义ID请求');
          resolve();
        },
        fail: (err) => {
          console.error('启用通知失败:', err);
          reject(err);
        },
      });
    });

    uni.onBLEConnectionStateChange((res) => {
      console.log('连接状态变化:', res);
      if (!res.connected) {
        console.error('设备已断开:', res.deviceId);
        loadingPopup.value?.close();
        currentTab.value = 0;
        customId.value = '';
        isConfigTabDisabled.value = true;
      }
    });
  } catch (err) {
    loadingPopup.value?.close();
    console.error('连接失败:', JSON.stringify(err, null, 2));
    await showPopup("蓝牙连接超时，请稍后重试");
    isConfigTabDisabled.value = true;
    closeConnectAndSearchBlue();
    return;
  }
  loadingPopup.value?.close();
};

const closeConnectAndSearchBlue = () => {
  if (deviceId.value) {
    uni.closeBLEConnection({
      deviceId: deviceId.value,
      success: () => {
        console.log('断开设备:', deviceId.value);
      },
      fail: (err) => {
        console.error('断开连接失败:', JSON.stringify(err, null, 2));
      },
    });
  }

  deviceId.value = '';
  serviceId.value = '';
  writeCharId.value = '';
  readCharId.value = '';
  selectedDevice.value = null;
  getBluDevice();
};

const writeBLEData = async (data: number[]) => {
  try {
    return await new Promise<void>((resolve, reject) => {
      uni.writeBLECharacteristicValue({
        deviceId: deviceId.value,
        serviceId: serviceId.value,
        characteristicId: writeCharId.value,
        value: new Uint8Array(data).buffer,
        success: () => {
          console.log('写入数据:', data);
          resolve();
        },
        fail: (err) => {
          console.error('写入失败:', JSON.stringify(err, null, 2));
          reject(new Error(`写入失败: ${JSON.stringify(err)}`));
        },
      });
    });
  } catch (err) {
    console.error('writeBLEData 错误:', JSON.stringify(err, null, 2));
    throw err;
  }
};

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const performDHNegotiation = async () => {
  console.log('DH 协商已禁用，跳过密钥协商步骤');
  md5Key.value = [];
};

const waitForServerKey = () => {
  return new Promise<number[]>((resolve) => {
    console.log('DH 协商已禁用，无需等待固件公钥');
    resolve([]);
  });
};

const sendCustomData = async (data: number[] = [0xFF, 0xA1]) => {
  let remainingData = data;
  let packetCount = 0;
  while (remainingData.length > 0) {
    const packet = writeData(
        PACKAGE_VALUE,
        SUBTYPE_CUSTOM_DATA,
        getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, remainingData.length > (actualMtu.value - 3)),
        sequence.value,
        remainingData.length,
        remainingData
    );
    const sub = isSubcontractor(packet, false, sequence.value, false);
    console.log(
        `发送自定义数据 - 分包${++packetCount} (seq=${sequence.value}, len=${sub.len}, flag=${sub.flag}, mtu=${actualMtu.value}):`,
        sub.lenData
    );
    await writeBLEData(sub.lenData);
    sequence.value++;
    if (sub.flag) {
      console.log(`剩余数据:`, sub.laveData);
      remainingData = sub.laveData;
    } else {
      remainingData = [];
    }
  }
};

const sendDataWithSubcontract = async (
    payloadBytes: number[],
    type: number,
    subType: number,
    deviceId: string,
    serviceId: string,
    characteristicId: string
) => {
  const frameCtrl = getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, false);

  const blufiPDU = writeData(
      type,
      subType,
      frameCtrl,
      sequence.value,
      payloadBytes.length,
      payloadBytes
  );

  console.log(
      `[sendDataWithSubcontract] Prepared Blufi PDU (Blufi Seq=${sequence.value}, Type=${type}, SubType=${subType}, PayloadLen=${payloadBytes.length}):`,
      blufiPDU
  );

  let remainingBleDataForThisPDU = [...blufiPDU];

  while (remainingBleDataForThisPDU.length > 0) {
    const sub = isSubcontractor(remainingBleDataForThisPDU, false, sequence.value, false);
    let dataForThisWrite = [...sub.lenData];

    console.log(
        `  Sending BLE fragment for Blufi Seq ${sequence.value} (ChunkLen=${dataForThisWrite.length}, MoreBLEFrags=${sub.flag}):`,
        dataForThisWrite
    );

    await new Promise<void>((resolve, reject) => {
      uni.writeBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId,
        value: new Uint8Array(dataForThisWrite).buffer,
        success: () => {
          console.log('写入成功');
          resolve();
        },
        fail: (err) => {
          console.error('写入失败:', err);
          reject(err);
        },
      });
    });
    remainingBleDataForThisPDU = sub.laveData;
    console.log(`[sendDataWithSubcontract] Blufi PDU for Seq ${sequence.value} fully sent. Incrementing sequence.`);
    sequence.value++;
  }
};

const startConfig = async () => {
  console.log('开始配网，设备ID:', deviceId.value, 'SSID:', ssid.value, '密码:', password.value, '自定义ID:', customId.value);
  try {
    if (!deviceId.value){
		await showWifiPopup("请先选择设备");
		return;
	} 

    if (!ssid.value.trim()) {
      await showWifiPopup("请输入Wi-Fi名称");
      return;
    }
    if (!password.value.trim()) {
      await showWifiPopup("请输入Wi-Fi密码");
      return;
    }

    if (!customId.value) {
      await showPopup("蓝牙连接已断开，请重试");
      getBluDevice();
      return;
    }

    const userInfo = uni.getStorageSync("userInfo");
    console.log(userInfo);
    const res = await getDeviceDetail(customId.value);
    bindStatus.value = res.data.bindStatus;
    console.log('设备详情:', res);
    if (res.code === '200' && bindStatus.value === 1 && res.data.userId !== userInfo.id) {
      await showPopup("当前设备已被绑定，请解绑后重试");
      getBluDevice();
      isConfigTabDisabled.value = true;
      return;
    }

    loadingMessage.value = '正在配网';
    loadingPopup.value?.open();
    sequence.value = 1;

    await fetchBLEMTU(deviceId.value);
    console.log(`将使用 MTU: ${actualMtu.value} 字节`);

    await new Promise<void>((resolve, reject) => {
      uni.notifyBLECharacteristicValueChange({
        deviceId: deviceId.value,
        serviceId: serviceId.value,
        characteristicId: readCharId.value,
        state: true,
        success: () => {
          console.log('启用通知成功');
          resolve();
        },
        fail: (err) => {
          console.error('启用通知失败:', err);
          reject(new Error('启用通知失败'));
        },
      });
    });

    const secModeData = [0x00];
    await sendDataWithSubcontract(secModeData, PACKAGE_CONTROL_VALUE, SUBTYPE_SET_SEC_MODE, deviceId.value, serviceId.value, writeCharId.value);
    console.log('已发送安全模式');

    const opModeData = [0x01];
    await sendDataWithSubcontract(opModeData, PACKAGE_CONTROL_VALUE, SUBTYPE_WIFI_MODEl, deviceId.value, serviceId.value, writeCharId.value);

    const ssidData = encodeUTF8(ssid.value.trim());
    console.log('发送WiFi SSID:', ssidData);
    await sendDataWithSubcontract(ssidData, PACKAGE_VALUE, SUBTYPE_SET_SSID, deviceId.value, serviceId.value, writeCharId.value);

    const pwdData = encodeUTF8(password.value.trim());
    console.log('发送WiFi密码:', pwdData);
    await sendDataWithSubcontract(pwdData, PACKAGE_VALUE, SUBTYPE_SET_PWD, deviceId.value, serviceId.value, writeCharId.value);

    const endPacket = writeData(
        PACKAGE_CONTROL_VALUE,
        SUBTYPE_END,
        getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, false),
        sequence.value++,
        0,
        []
    );
    console.log('发送结束标志:', endPacket);
    await writeBLEData(endPacket);
    await waitForConfigResult();
  } catch (err: any) {
    console.error('配网失败:', err);
    loadingPopup.value?.close();
    isConfigTabDisabled.value = true;
  }
};

const waitForConfigResult = () => {
  return new Promise<void>((resolve, reject) => {
    let lastSequence = sequence.value - 1;
    const handler = async (res: any) => {
      const value = new Uint8Array(res.value);
      const type = value[0] & 0x03;
      const subType = (value[0] >> 2) & 0x3F;
      const sequenceNum = value[2];
      console.log('收到配网结果通知:', {
        type,
        subType,
        sequenceNum,
        value: Array.from(value)
      });
      lastSequence = sequenceNum;

      if (type === PACKAGE_VALUE && subType === 15) {
        uni.hideLoading();
        uni.offBLECharacteristicValueChange(handler);

        await showConnetSuccessPopup();

        try {
          if (bindStatus.value === 0) {
            const bindRes = await bindByDeviceId(customId.value);
            console.log('绑定结果:', bindRes);
            if (bindRes.code === '200') {
              isConfigTabDisabled.value = false;
              console.log("绑定成功");
              await showBindSuccessPopup();
              popupRef.value?.close();
              uni.navigateTo({
                url: `/pages/complateProfile/complateProfile`,
              });
            } else {
              isConfigTabDisabled.value = true;
              await showPopup("设备已被他人绑定，请确认设备状态");
              console.log(`绑定失败，错误码: ${bindRes.code}, 消息: ${bindRes.msg}`);
            }
          } else {
            uni.switchTab({
              url: `/pages/myDevices/myDevices`,
            });
          }
          currentTab.value = 0;
          ssid.value = '';
          password.value = '';
          deviceId.value = '';
          customId.value = '';
          serviceId.value = '';
          writeCharId.value = '';
          readCharId.value = '';
          selectedDevice.value = null;
          bindStatus.value = null;
          resolve();
		  return;
        } catch (error) {
          console.error("绑定设备出错:", error);
          uni.showToast({ title: '绑定设备失败', icon: 'none' });
          currentTab.value = 0;
          ssid.value = '';
          password.value = '';
          deviceId.value = '';
          customId.value = '';
          serviceId.value = '';
          writeCharId.value = '';
          readCharId.value = '';
          bindStatus.value = null;
          selectedDevice.value = null;
          isConfigTabDisabled.value = true;
          resolve();
        }
      } else if (type === PACKAGE_VALUE && subType === 18) {
        console.error('配网失败，固件错误代码:', Array.from(value.slice(4)));
        uni.offBLECharacteristicValueChange(handler);
        await showPopup("配网失败");
        isConfigTabDisabled.value = true;
      } else {
        console.warn(`未识别的通知: type=${type}, subType=${subType}, value=`, Array.from(value));
      }
    };

    uni.onBLECharacteristicValueChange(handler);
    setTimeout(() => {
	  loadingPopup.value?.close();
      isConfigTabDisabled.value = true;
      uni.offBLECharacteristicValueChange(handler);
      showPopup("配网失败");
    }, 8000);
  });
};

const showPopup = async (message: string, duration: number = 1500) => {
  if (!popupRef.value) {
    console.warn('Popup reference is not available');
    return;
  }
  popupMessage.value = message;
  popupRef.value.open();
  await delay(duration);
  popupRef.value.close();
};

const showConnetSuccessPopup = async () => {
  if (!connectSuccessPopup.value) {
    console.warn('Popup reference is not available');
    return;
  }
  connectSuccessPopup.value.open();
  await delay(1500);
  connectSuccessPopup.value.close();
};

const showBindSuccessPopup = async (duration: number = 1500) => {
  if (!bindSuccessPopup.value) {
    console.warn('Popup reference is not available');
    return;
  }
  bindSuccessPopup.value.open();
  await delay(duration);
  bindSuccessPopup.value.close();
};

const showWifiPopup = async (message: string, duration: number = 1500) => {
  if (!wifiWarnPopup.value) {
    console.warn('Popup reference is not available');
    return;
  }
  wifiWarnMsg.value = message;
  wifiWarnPopup.value.open();
  await delay(duration);
  wifiWarnPopup.value.close();
};

const checkLocationServiceEnabled = () => {
  const isAndroid = uni.getSystemInfoSync().platform === 'android';
  if (isAndroid) {
    wx.getLocation({
      type: 'wgs84',
      success: () => {
        console.log('系统定位已开启');
      },
      fail: (err) => {
        console.log('可能系统定位未开启', err);
        uni.showModal({
          title: '系统定位未开启',
          content: '请前往系统设置打开定位服务，否则无法搜索蓝牙设备',
        });
      }
    });
  }
};

const closeBleConnect = () => {
  if (deviceId.value) {
    uni.closeBLEConnection({
      deviceId: deviceId.value,
      success: () => {
        console.log('断开设备:', deviceId.value);
      },
    });
  }
};

onMounted(() => {
  checkLocationServiceEnabled();
  getBluDevice();
});

onUnmounted(() => {
  if (isDiscovering.value) {
    uni.stopBluetoothDevicesDiscovery({
      success: () => {
        console.log('停止设备扫描');
        isDiscovering.value = false;
      },
    });
  }
  if (deviceId.value) {
    uni.closeBLEConnection({
      deviceId: deviceId.value,
      success: () => {
        console.log('断开设备:', deviceId.value);
      },
    });
  }
  deviceList.length = 0;
  uni.offBluetoothDeviceFound();
  uni.offBLECharacteristicValueChange();
});
</script>

<style scoped>
.container {
  padding: 20rpx 0;
  background: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.tab-bar-container {
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.tab-item {
  flex: 1;
  padding: 20rpx 0;
  font-size: 32rpx;
  color: #333;
  text-align: center;
  position: relative;
  transition: color 0.3s;
}

.tab-item.active {
  color: #007aff;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 50rpx;
  height: 4rpx;
  background: #007AFF;
  border-radius: 0rpx 0rpx 0rpx 0rpx;
}

.tab-item.disabled {
  color: #ccc;
  pointer-events: none;
}

.content-area {
  background: #f5f5f5;
}

.device-list-content {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.device-scroll-view {
  max-height: calc(100vh - 400rpx);
}

.device-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 2rpx solid #eee;
}

.selected-device-display {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.device-icon {
  width: 100rpx;
  height: 100rpx;
  min-width: 100rpx;
  min-height: 100rpx;
  object-fit: cover;
  margin-right: 20rpx;
  background-color: #f0f0f0;
}

.device-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.device-name {
  font-size: 32rpx;
  color: #000;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.empty-list {
  padding: 60rpx 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  background-color: #fff;
}

.network-config-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.form {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.form-item text {
  width: 150rpx;
  font-size: 30rpx;
  color: #333;
  margin-right: 10rpx;
}

.form-item input {
  flex: 1;
  font-size: 30rpx;
  height: 90rpx;
  background: #F4F4F4;
  border-radius: 30rpx;
  padding: 0 80rpx 0 40rpx; /* Add right padding for eye icon in password input */
  box-sizing: border-box;
  width: 100%; /* Ensure consistent width */
}

.submit-btn {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  font-size: 32rpx;
  border-radius: 48rpx;
  border: none;
  margin-top: 60rpx;
}

.device-icon-wrapper {
  width: 110rpx;
  height: 110rpx;
  min-width: 110rpx;
  min-height: 110rpx;
  margin-right: 25rpx;
  background-color: #f0f0f0;
  border: 1px dashed #dcdcdc;
  border-radius: 12rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.device-actual-image {
  width: 98rpx;
  height: 78rpx;
  object-fit: cover;
  border-radius: 2rpx;
}

.tab-bar-spacer {
  width: 100%;
  height: 100%;
  background: #E5E5E5;
  border-radius: 0rpx 0rpx 0rpx 0rpx;
}

.loading-box {
  width: 548.51rpx;
  height: 303rpx;
  background-image: url(/static/loading_background.png);
  background-size: 100% 100%;
  background-position: center;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.wifi-input-box {
  width: 553rpx;
  height: 80rpx;
  background-image: url(/static/icons/wifi_background.png);
  background-size: 100% 100%;
  background-position: center;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 88rpx 0rpx 0rpx 0rpx;
  position: relative;
  transform: translateY(-20%);
}

.text-overlay {
  width: 380rpx;
  height: 89rpx;
  line-height: 43rpx;
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 700;
  font-size: 30rpx;
  color: #FFFFFF;
  text-align: center;
  font-style: normal;
  text-transform: none;
  position: absolute;
  top: 210rpx;
  left: 100rpx;
}

.wifi-text-overlay {
  width: 227rpx;
  height: 77rpx;
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 700;
  font-size: 30rpx;
  color: #FFFFFF;
  line-height: 43rpx;
  text-align: center;
  font-style: normal;
  text-transform: none;
}

.success {
  width: 100rpx;
  height: 100rpx;
  position: absolute;
  top: 86rpx;
  left: 241rpx;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-icon {
  width: 100rpx;
  height: 100rpx;
  animation: spin 2s linear infinite;
  display: inline-block;
}

.custom-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
}

.password-input-wrapper {
  position: relative; /* Positioning context for eye icon */
  flex: 1; /* Match the width of Wi-Fi name input */
}

.eye-icon {
  position: absolute;
  right: 20rpx; /* Position inside the input, 20rpx from right edge */
  top: 50%;
  transform: translateY(-50%); /* Center vertically */
  width: 46rpx;
  height: 46rpx;
  cursor: pointer;
  z-index: 10;
}

</style>